I will assume a basic understanding of R Markdown. If you need a refresher or reminder of markdown syntax, see the rmarkdown cheatsheet. This is intended as a brief reference for intermediate to advanced users looking to take their R Markdown game to the next level. Think, a 200 or 300 series course code.
“Hi, yes, I have a grievance I would like to file:
I signed up to use R, not- yaml, css, js, bib, markdown, and html.”— Nick Spyrison, 2018. Loosely transcribed.
Suffice it to say that it took and still takes me aggravating amounts of time just to get a new .rmd format compiling, let alone polish options and sizes. I am writing this blog and the corresponding repository to allay such frustrations for my future self and hopefully some others as well.
… navigate R Markdown output nuances.
I must respond with something slightly cliche, use the right tool for the right job. Problems and tools come in all shapes and sizes. While frustrating at times, these frictions are the right of passage we undergo to achieve a rich diversity and quality of formats. We should also note that they exist for completely valid reasons considering the sometimes nebulous complexity of the moving pieces between code and its output. This document focuses on formats and nuances of using R markdown files (.rmd), which stems primarily from the work of Yihui Xie, many thanks Yihui. I attempt to mitigate friction by providing text and directory examples.
“Hardcoded” content vs generation at compilation:
I recognize this debatably goes against some of the benefits of R markdown. However, if you are a less-than expert level R coder, at least consider the following to minimize frustration and overhead time:
Below I outline some of the more common chunk options and try to explain what they do and list expected values.
For a more lengthy digest consult Yihui’s chapter ‘Options’.
\```{r setup, include=FALSE}
## Load packages here.
library(knitr)
knitr::opts_chunk$set(
###### TEXT DISPLAY:
echo = TRUE, # Echo code executed?
message = FALSE, # Display message text?
warning = FALSE, # Display warning text?
error = FALSE, # Display error text?
strip.white = TRUE, # Remove preceeding and trailing line returns from chunks?
include = TRUE, # Include chunk output in compiled document?
tidy = FALSE, # Tidy-up chunk code format?
## Expects: FALSE, TRUE=formatR::tidy_source(), "styler"= styler::style_text().
results = "hide", # Chunk results, render formating:
## Expectes: "markup"; TeX env, "asis"; in line,
## "hold"; output to the bottom of code, "hide"; no display.
###### FIGURES AND PLOTS:
#### Scope: `fig.*` arguments apply to figures produced directly in the .rmd document.
fig.align = "center", # Figure alignment. Expects: "left", "right", "center", "default"
fig.width = 8, # Figure width [in inches, default: 5]
fig.height = 5, # Figure height [in inches, default: 5]
# fig.asp, = 1.62 # Figure aspect ratio. do not use with both width and height.
fig.show = "hold", # Figure output formating
## Expects "asis"; where generated, "hold"; hold plot display to end of chunk,
## "animate"; wrap all plots into an animation, "hide"; no display.
fig.pos = "h", # "h"olds the postion closer than floating (default: "")
out.extra = "", # Additionally required for fig.pos = "h"
#### Scope: `out.*` arguments apply to external images (.jpg, .png, .gif) files
#### AS WELL AS, figures produced directly in the .rmd document.
out.width = "100%" # Expects fromats like: "3in", "8cm", "80%", ".8\\linewidth", for HTML: "300px"
#out.height = "100%", # Expects fromats like: "3in", "8cm", "80%", ".8\\linewidth", for HTML: "300px"
## Try only specifying width or height before applying both.
###### COMPILING AND SOFT DISPLAY:
collapse = TRUE, # Collapse chunk sections in the .rmd file?
cache = FALSE, # Keep cache files? (default: TRUE)
## If output doesn't seem to reflect recent changes, set to FALSE (may also slow compilation time)
cache.lazy = FALSE # Lazily load objects? FALSE is eager loading. (default: TRUE).
## If large objects are not behaving, set to FALSE.
)
\```
\```{r setup_condensed, include=F}
## Load packages here.
library(knitr);
knitr::opts_chunk$set(
message = F, warning = F, error = F,
results = "asis" # Opts: "asis", "markup", "hold", "hide"
fig.align = "center", # Opts: "left", "right", "center", "default"
fig.width = 8, fig.height = 5,
out.width = "100%"
fig.pos = "h", out.extra = "", # Figures forced closer to chunk location.
collapse = TRUE, cache = FALSE, cache.lazy = FALSE
)
\```
Remember: These same options can be customized for each code chunk
ie. \```{r chunk_name, include=T, cache=F, eval=F, results="markup"}
pdf_document2Scope: Static .pdf documents compiled with the bookdown::pdf_document2 format.
Requires:
— in YAML header:
output: bookdown::pdf_document2 ## 'pdf_document2' changes how fig references work to /ref()
bibliography: bib_example.bib ## Allows bibliography references
— in directory:
./figures/myFigure1.png
./figures/<all other .png, .jpg, .gif files>
./<myBibliographyFile.bib>
[@matejka_same_2017].
[Section reference](#sec:pdf)
{#sec:rmdRef} after the header text.\ref{sec:rmdRef} should create a hyperlinked number for the section. (no ‘#’ in ‘#sec’ and no ‘@’ in \@ref{} as found in some other formats).\ref(fig:doge) (no ‘@’; in \@ref(fig:doge) as found in some other formats).
A figure caption: wow, such figure, much caption.
Alternatively in a pdf2_document .rmd file you can define long or complex captions outside of a chunk header:
R chunk arguments. Good for when you do fancy formating or inline \(\LaTeX\) code. Apparently not compatible with ‘html_document’.
(ref:thisIsDog-cap)
xaringanScope: Presentation slides (.html) produced with xaringan::moon_reader.
Requires:
— in YAML:
output: xaringan::moon_reader
xaringan syntax, ninja style'- ', the space is important.
' - '.-- to create an incremental slide break, hiding later content.Xaringan is very sensitive to white space, make sure to leave plenty of “breathing room”; an empty line before and after almost every bit of content.Xaringan is sensitive to comments; use <!-- <comments> --> sparingly!Scope: Presentation slides (.html) produced with xaringan::moon_reader.
Requires:
— in YAML:
output:
xaringan::moon_reader:
css:
- ninjutsu ### or your next favorite .css file, like: # - "assets/xaringan-themer.css"`
- "assets/custom.css"
— in directory:
./assets/custom.css
.funtions[], by nesting content inside, with '.functionNm[', and ']' each on their own line:.pull-left[
Left column content...
]
.pull-right[
...and right column content.
]
.pull-left[], .pull-right[] are already defined as general css functions../assests/custom.css, for instance:/* Create your own .css functions, like these for changing the size of body text:*/
.larger {font-size: 120%}
.smaller {font-size: 80% }
Because .yaml headers, xaringan, and some general .rmd formating is so sensitive to the precice number of spaces and line returns:
RStudio > Tools > Global Options... > Code > Display > Show whitespace characters [x]Because navigating and traversing documents takes too long:
# Introduction … ## Motivation# Initialize vars -----Thanks for the read. Let me know if this helped, or if there are other topics you need help getting started with. Drop me a line by email at [spyrison@gmail.com](Link text).
A bit off-topic, but it bears repeating. Practice good code hygiene. If you are not yet familiar with this term it doubly applies to you. I suggest reading the Tidyverse Style Guide most of it may seem pedantic, but they are listed for a reason. Not everything will be equally important based on the size of your file, directory, and the number of collaborators, but it’s better to form good habits early.
I strongly, strongly suggest at least:
RStudio > Tools > Global Options... > Code > Display > Show margin [x]a <- 5, not a = 5a <- 5, not 5 -> a# Initialize vars -----# Introduction … ## MotivationBecause I have defined a .bib file in my yaml header the items in my .bib file are included below. Note that you do have to define a # References header at the bottom of the .rmd if so desired.
While using pdf_document2 I think only cited refences will be printed rather than all items in the .bib file.
Matejka, Justin, and George Fitzmaurice. 2017. “Same Stats, Different Graphs: Generating Datasets with Varied Appearance and Identical Statistics Through Simulated Annealing.” In Proceedings of the 2017 CHI Conference on Human Factors in Computing Systems - CHI ’17, 1290–4. Denver, Colorado, USA: ACM Press. https://doi.org/10.1145/3025453.3025912.